//
//  CalendarView.m
//  中行客服端
//
//  Created by rimi on 16/7/27.
//  Copyright © 2016年 ZH. All rights reserved.
//

#import "CalendarView.h"
#import "CalendarCollectionViewCell.h"
#import "ZZConfig.h"
@interface CalendarView ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,strong)NSArray           *weekArray;

@property(nonatomic,strong)UICollectionView  *collectionView;

@property(nonatomic,strong)NSMutableArray    *dayArray;

@property(nonatomic,strong)NSCalendar        *myCalendar;

@property(nonatomic,strong)NSDate            *falgDate;

@property(nonatomic,strong)NSString          *lastDateStr;

@property (nonatomic, strong) UILabel        *dateLabel;
@end


@implementation CalendarView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = COLOR(216, 221, 227, 1);
        self.layer.cornerRadius = 15;
        self.layer.masksToBounds = YES;
        [self initializeDataSource];
        [self updaUI];
    }
    return self;
}
-(void)initializeDataSource{
    _weekArray = @[@"SUN",@"TUE",@"WED",@"THU",@"FRI",@"SAT",@"MON"];
    _dayArray = [[NSMutableArray alloc]init];
    
    _myCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    _falgDate = [NSDate date];
    
    NSInteger total = [self getDaysNumberForMonth];
    NSInteger firstWeek = [self getFirstdayWeekInMonth];
    
    [self updateCalendarCollectionViewWithDays:total firstWeek:firstWeek];
    
}


-(void)updaUI{
  
    NSDateComponents *dateComponents = [_myCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:_falgDate];
    
    _dateLabel = [[UILabel alloc]initWithFrame:CGRectMake(40, 10, 173, 40)];
    if (dateComponents.month > 0 && dateComponents.month < 10) {
        _dateLabel.text = [NSString stringWithFormat:@"%ld-0%ld",dateComponents.year,dateComponents.month];
    } else {
    _dateLabel.text = [NSString stringWithFormat:@"%ld-%ld",dateComponents.year,dateComponents.month];
    }
    _dateLabel.textAlignment = NSTextAlignmentCenter;
    _dateLabel.font = [UIFont systemFontOfSize:18];
    _dateLabel.textColor = [UIColor whiteColor];
    [self addSubview:_dateLabel];
    
    
    UIButton *lastButton = [UIButton buttonWithType:UIButtonTypeCustom];
    lastButton.tag = 360;
    lastButton.frame = CGRectMake(20, 20, 20, 20);
    [lastButton setImage:[UIImage imageNamed:@"left_arrow.png"] forState:UIControlStateNormal];
    [lastButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [lastButton addTarget:self action:@selector(changeMonthButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:lastButton];
    
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.tag = 361;
    nextButton.frame = CGRectMake(213 , 20, 20, 20);
    [nextButton setImage:[UIImage imageNamed:@"right_arrow.png"] forState:UIControlStateNormal];
    [nextButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(changeMonthButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:nextButton];

    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 40, 253, 30)];
    imageView.image = [UIImage imageNamed:@"底_14.png"];
    [self addSubview:imageView];
    
    for (NSInteger i = 0; i < 7; i ++) {
        UIButton *weekButton = [UIButton buttonWithType:UIButtonTypeSystem];
        weekButton.frame = CGRectMake(35*i, 0, 35, 30);
        [weekButton setTitle:_weekArray[i] forState:UIControlStateNormal];
        [weekButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        weekButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [imageView addSubview:weekButton];
    }
    
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(34, 34);
    flowLayout.minimumLineSpacing = 1;
    flowLayout.minimumInteritemSpacing = 1;
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(3, 67, 247, 175) collectionViewLayout:flowLayout];
    _collectionView.layer.cornerRadius = 5;
    _collectionView.layer.borderWidth = 1;
    _collectionView.layer.borderColor = [UIColor whiteColor].CGColor;
    [_collectionView registerClass:[CalendarCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    _collectionView.backgroundColor = COLOR(218, 225, 230, 1);
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self addSubview:_collectionView];
    
    
    
}

#pragma mark -- action

-(void)changeMonthButtonAction:(UIButton *)sender{
    
//    _collectionView.backgroundColor = [UIColor whiteColor];
    if (sender.tag == 360) {
        NSDate *lastDate = [self getLastMonthDate];
        
        _falgDate = lastDate;
        
    } else {
        NSDate *nextDate = [self getNextMonthDate];
        _falgDate = nextDate;
    }
    
    NSInteger total = [self getDaysNumberForMonth];
    NSInteger firstWeek = [self getFirstdayWeekInMonth];
    
    [self updateCalendarCollectionViewWithDays:total firstWeek:firstWeek];

}

#pragma mark -- Method

-(void)updateCalendarCollectionViewWithDays:(NSInteger)days firstWeek:(NSInteger)firstWeek{
    [_dayArray removeAllObjects];
    
    for (int i = 0; i<days+firstWeek-1; i++) {
        if (i<firstWeek-1) {
            [_dayArray addObject:@""];
        } else{
            [_dayArray addObject:[NSString stringWithFormat:@"%ld",i-firstWeek+2]];
        }
    }
    
    [_collectionView reloadData];
}

-(NSInteger)getDaysNumberForMonth{
    return [_myCalendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:_falgDate].length;
}


-(NSInteger)getFirstdayWeekInMonth{
    NSDateComponents *dateComponents = [_myCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:_falgDate];
    
//    _dateLabel.text = [NSString stringWithFormat:@"%ld-%ld",dateComponents.year,dateComponents.month];
    if (dateComponents.month > 0 && dateComponents.month < 10) {
        _dateLabel.text = [NSString stringWithFormat:@"%ld-0%ld",dateComponents.year,dateComponents.month];
    } else {
        _dateLabel.text = [NSString stringWithFormat:@"%ld-%ld",dateComponents.year,dateComponents.month];
    }

    
    NSInteger currenDay = dateComponents.day;
    NSTimeInterval time =-(currenDay-1)*24*3600;
    NSDate *newDate = [_falgDate dateByAddingTimeInterval:time];
    
    NSDateComponents *newComponents = [_myCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:newDate];
    
    return newComponents.weekday;
}

-(NSDate *)getNextMonthDate{
    NSDateComponents *dateComponents = [_myCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:_falgDate];
    dateComponents.day = 1;
    if (dateComponents.month == 12) {
        dateComponents.month = 1;
        dateComponents.year = dateComponents.year+1;
    } else {
        dateComponents.month = dateComponents.month +1;
    }
    NSDate *nextDate = [_myCalendar dateFromComponents:dateComponents];
    return nextDate;
}

-(NSDate *)getLastMonthDate{
    NSDateComponents *dateComponents = [_myCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:_falgDate];
    dateComponents.day = 1;
    if (dateComponents.month == 1) {
        dateComponents.month = 12;
        dateComponents.year = dateComponents.year-1;
    } else {
        dateComponents.month = dateComponents.month -1;
    }
    
    
    NSDate *lastDate = [_myCalendar dateFromComponents:dateComponents];
    return lastDate;
    
}

/**data转换成字符串*/
- (NSString *)dateWithString:(NSDate *)date{
    NSString *string;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    string = [formatter stringFromDate:date];
    return string;
}

#pragma mark -- UICollectionViewDelegate,UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dayArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CalendarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    if (![_dayArray[indexPath.row] isEqualToString:@""]) {
        cell.backgroundColor = COLOR(242, 242, 242, 1);
    }
    /** 判断当前是哪一年，哪一月，那一天，让其颜色变成灰色 */
    NSDate *date = [NSDate date];
    if (indexPath.row >= 0 && indexPath.row <= 9) {
        NSString *str = [NSString stringWithFormat:@"0%ld",indexPath.row];
        NSString *string = [NSString stringWithFormat:@"%@-%@",_dateLabel.text,str];
        if ([string isEqualToString:[self dateWithString:date]]) {
            cell.backgroundColor = [UIColor grayColor];
        }
        
    } else {
        NSString *string = [NSString stringWithFormat:@"%@-%ld",_dateLabel.text,indexPath.row];
        NSDate *date = [NSDate date];
        if ([string isEqualToString:[self dateWithString:date]]) {
            cell.backgroundColor = [UIColor grayColor];
        }
    }
    
    cell.titleLabel.text = [NSString stringWithFormat:@"%@",_dayArray[indexPath.row]];
    cell.titleLabel.textColor = [UIColor blackColor];

    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CalendarCollectionViewCell *cell = (CalendarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = COLOR(138, 183, 217, 1);
    cell.titleLabel.textColor = [UIColor whiteColor];
    NSDictionary *dic = @{@"text":[NSString stringWithFormat:@"%@-%@",_dateLabel.text,_dayArray[indexPath.row]]};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"labelText" object:nil userInfo:dic];

}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CalendarCollectionViewCell *cell = (CalendarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.titleLabel.textColor = [UIColor blackColor];
    cell.backgroundColor = COLOR(242, 242, 242, 1);
    /** 判断当前是哪一年，哪一月，那一天，让其颜色变成灰色 */
    NSDate *date = [NSDate date];
    if (indexPath.row >= 0 && indexPath.row <= 9) {
        NSString *str = [NSString stringWithFormat:@"0%ld",indexPath.row];
        NSString *string = [NSString stringWithFormat:@"%@-%@",_dateLabel.text,str];
        if ([string isEqualToString:[self dateWithString:date]]) {
            cell.backgroundColor = [UIColor grayColor];
        }
        
    } else {
        NSString *string = [NSString stringWithFormat:@"%@-%ld",_dateLabel.text,indexPath.row];
        NSDate *date = [NSDate date];
        if ([string isEqualToString:[self dateWithString:date]]) {
            cell.backgroundColor = [UIColor grayColor];
        }
    }


    
}


@end
